package com.jy.modules.cims.common.controller;


import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.component.common.service.TCMmContractService;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCostaccountViewService;
import com.jy.modules.cims.component.common.service.TCMmDealCostService;
import com.jy.modules.cims.component.sysAssist.CSysAssistImpl;
import com.jy.modules.cims.data.common.dto.TCMmContractDTO;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCostaccountViewDTO;
import com.jy.modules.cims.data.common.dto.TCMmCostdealAdOrgdealDTO;
import com.jy.modules.cims.data.common.dto.TCMmDealCostDTO;
import com.jy.platform.api.org.SessionAPI;
import com.jy.platform.api.org.UserInfo;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;


/**
 * @classname: TCMmCostaccountViewController
 * @description: 定义  COSTACCOUNT_VIEW 控制层
 * @author:  dell
 */
@Controller
@Scope("prototype")
@RequestMapping("/costaccViewLoan")
public class TCMmCostaccountLoanViewController extends BaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmCostaccountLoanViewController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCostaccountViewService")
    private TCMmCostaccountViewService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.sysAssist.CSysAssistImpl")
    private CSysAssistImpl csysAssistimpl;
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
    private TCMmCooperorgDealService cooperorgDealService; 
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmContractService")
    private TCMmContractService contractService ;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmDealCostService")
    private TCMmDealCostService dealCostservice;
    @Autowired
    private SessionAPI sesisonApi;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/creditManage/queryTCMmCostAccount");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/creditManage/addTCMmCostAccount");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditManage/updateTCMmCostAccount");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditManage/viewTCMmCostAccount");
        }
        
        return model;
    }
    
    /**
     * @author dell
     * @description:查询分页列表
     * @date 2015-02-02 20:26:25
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListCostaccountView")
    @ResponseBody
    public DataMsg queryListCostaccountView(HttpServletRequest request, TCMmCostaccountViewDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	String dealType = this.getParameterString("dealType");
    	
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setDealType(dealType);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmCostaccountViewDTO> list = service.searchCostaccountViewByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    



 

    /**
     * @author dell
     * @description:删除
     * @date 2015-02-02 20:26:25
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteDealCost")
    @ResponseBody
    public DataMsg deleteCostaccountView(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 dealCostservice.deleteTCMmDealCostByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteCostaccountView异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author dell
     * @description:通过主键查询 其明细信息
     * @date 2015-02-02 20:26:25
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
    	  ModelAndView model = new ModelAndView();
		try {
			TCMmDealCostDTO costdto = dealCostservice
					.queryTCMmDealCostByPrimaryKey(id);
			Map<String, Object> searchParams = new HashMap<String, Object>();
			// 查询合作机构交易流水表
			TCMmCooperorgDealDTO orgDealDTO = new TCMmCooperorgDealDTO();
			orgDealDTO.setDealCode(costdto.getDealStreamCode());
			searchParams.put("dto", orgDealDTO);
			List<TCMmCooperorgDealDTO> orgDealDTOList = cooperorgDealService.searchTCMmCooperorgDeal(searchParams);
			orgDealDTO = orgDealDTOList.get(0);
			// 查询合约信息
			TCMmContractDTO contractDTO = new TCMmContractDTO();
			contractDTO.setContractCode(orgDealDTO.getContractCode());
			searchParams.put("dto", contractDTO);
			List<TCMmContractDTO> contractDTOlist = contractService.searchTCMmContract(searchParams);
			contractDTO = contractDTOlist.get(0);
			// 将信息放入 model 以便于传至页面 使用
			TCMmCostdealAdOrgdealDTO dto = this.getdto(costdto, contractDTO);
			dto.setId(id);
			model.addObject("dto", dto);
		}catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    /**
     * @author zhuwenbin
     * @description:组装交易结算信息和合约信息
     * @date 2015-02-02 14:49:23
     * @param costdto,contractDTO
     * @return
     */
    public TCMmCostdealAdOrgdealDTO getdto(TCMmDealCostDTO costdto,TCMmContractDTO contractDTO){
    	
    	TCMmCostdealAdOrgdealDTO dto = new TCMmCostdealAdOrgdealDTO();
    	dto.setAgreementCode(contractDTO.getAgreementCode());
    	dto.setContractCode(contractDTO.getContractCode());
    	dto.setCooperorgCode(contractDTO.getCooperorgCode());
    	dto.setPayer(contractDTO.getPayer());
    	dto.setReceiver(contractDTO.getReceiver());
    	dto.setInitiator(contractDTO.getInitiator());
    	dto.setGathering(contractDTO.getGathering());
    	
    	dto.setCostAccountNum(costdto.getCostAccountNum());
    	dto.setDealStreamCode(costdto.getDealStreamCode());
    	return dto;
    }
    
    

    /**
     * @author zhuwenbin
     * @description:费用结算新增交易结算表和合作机构交易流水表信息
     * @date 2015-02-02 14:49:23
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmCostdealAdOrgdeal")
    @ResponseBody
    public DataMsg insertTCMmCostdealAdOrgdeal(HttpServletRequest request, TCMmCostdealAdOrgdealDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	UserInfo userInfo =  sesisonApi.getCurrentUserInfo();
        	dto = (TCMmCostdealAdOrgdealDTO)super.initDto(dto);
        	
        	//获取交易流水号
        	String dealStreamNo = csysAssistimpl.getBizNo(CimsConstant.BIZNO_TYPE_DEAL);
        	 //组装交易结算流水信息表
        	TCMmDealCostDTO costDto = new TCMmDealCostDTO();
        	costDto.setDealStreamCode(dealStreamNo); 
        	costDto.setCostAccountNum(dto.getCostAccountNum());
        	costDto.setCreditPackageName(dto.getCreditPackageName());
        	costDto.setCreateTime(new Timestamp(System.currentTimeMillis()));
        	costDto.setCreateBy(userInfo.getUserName());
        	costDto.setAccountStatus(CimsConstant.SETTLESTATUS_NC);
        	costDto.setDealType(CimsConstant.DEAL_TYPE_SETTLE);
            //组装合作机构交易流水表信息
            TCMmCooperorgDealDTO orgdealDto = new TCMmCooperorgDealDTO();
            orgdealDto.setDealCode(dealStreamNo);
            orgdealDto.setContractCode(dto.getContractCode());
            orgdealDto.setAgreementCode(dto.getAgreementCode());
            orgdealDto.setCooperorgCode(dto.getCooperorgCode());
            
            service.insertTCMmCostdealAdOrgdeal(costDto,orgdealDto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(costDto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertTCMmCostdealAdOrgdeal异常：", e);
        }
        return dataMsg;
    }
    
    
    
    /**
     * @author dell
     * @description:编辑
     * @date 2015-02-02 14:49:23
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmDealCostAccountNum")
    @ResponseBody
    public DataMsg updateTCMmDealCostAccountNum(HttpServletRequest request, TCMmDealCostDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	UserInfo userInfo =  sesisonApi.getCurrentUserInfo();
        	dto = (TCMmDealCostDTO)super.initDto(dto);
        	dto.setModifyTime(new Timestamp(System.currentTimeMillis()));
        	dto.setModifyBy(userInfo.getUserName());
        	dealCostservice.updateTCMmDealCostAccountNum(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateTCMmDealCost异常：", e);
        }
        return dataMsg;
    }
}
